import React, { forwardRef, useImperativeHandle, useRef, useState, useEffect } from 'react';
import { message } from 'antd';
import MindMapVisualization from '../MindMapVisualization';
import FlowChartVisualization from '../FlowChartVisualization';
import OrgChartVisualization from '../OrgChartVisualization';
import SpecializedGraphVisualization from '../SpecializedGraphVisualization';

/**
 * 图谱可视化中心组件 - 兼容版本
 * 
 * 暂时移除插件系统依赖，保持基本功能正常运行
 * 后续可以重新集成插件系统
 */
const GraphVisualizationHub = forwardRef(({ 
  nodes = [], 
  edges = [], 
  graphType = 'knowledge',
  layout = 'force',
  layoutConfig = {},
  onLayoutChange,
  onNodeClick,
  onEdgeClick,
  onNodePositionUpdate,
  editable = false,
  width = '100%',
  height = 500,
  zoom = 1,
  animationSpeed = 0.3,
  isSimulationRunning = true,
  isFullscreen = false,
  onToggleFullscreen,
  errorHandler = (error) => console.error("图谱渲染错误:", error),
  useModularSystem = false // 暂时禁用模块化系统
}, ref) => {
  // 创建对子组件的引用
  const specializedGraphRef = useRef(null);
  const mindMapRef = useRef(null);
  const flowChartRef = useRef(null);
  const orgChartRef = useRef(null);
  
  // 添加渲染键来强制重新渲染
  const [renderKey, setRenderKey] = useState(0);
  
  // 监听布局变化，强制重新渲染
  useEffect(() => {
    console.log('🔍 GraphVisualizationHub useEffect 触发:', { 
      layout, 
      hasLayoutConfig: !!layoutConfig,
      nodesLength: nodes.length, 
      edgesLength: edges.length 
    });
    
    if (layout && nodes.length > 0) {
      console.log('✅ GraphVisualizationHub 布局变化，重新渲染图谱:', layout);
      setRenderKey(prev => {
        const newKey = prev + 1;
        console.log('🔄 GraphVisualizationHub 更新 renderKey:', prev, '->', newKey);
        return newKey;
      });
    } else {
      console.log('❌ GraphVisualizationHub 渲染条件不满足:', { layout, nodesLength: nodes.length });
    }
  }, [layout, layoutConfig, nodes.length, edges.length]);
  
  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    // 居中图谱
    centerGraph: () => {
      try {
        if (specializedGraphRef.current && specializedGraphRef.current.centerGraph) {
          specializedGraphRef.current.centerGraph();
        } else if (mindMapRef.current && mindMapRef.current.centerGraph) {
          mindMapRef.current.centerGraph();
        } else if (flowChartRef.current && flowChartRef.current.centerGraph) {
          flowChartRef.current.centerGraph();
        } else if (orgChartRef.current && orgChartRef.current.centerGraph) {
          orgChartRef.current.centerGraph();
        }
      } catch (error) {
        errorHandler(new Error(`居中图谱失败: ${error.message}`));
      }
    },
    
    // 开始动画
    startSimulation: (speed) => {
      try {
        if (specializedGraphRef.current && specializedGraphRef.current.startSimulation) {
          specializedGraphRef.current.startSimulation(speed);
        } else if (mindMapRef.current && mindMapRef.current.startSimulation) {
          mindMapRef.current.startSimulation(speed);
        } else if (flowChartRef.current && flowChartRef.current.startSimulation) {
          flowChartRef.current.startSimulation(speed);
        } else if (orgChartRef.current && orgChartRef.current.startSimulation) {
          orgChartRef.current.startSimulation(speed);
        }
      } catch (error) {
        errorHandler(new Error(`启动动画失败: ${error.message}`));
      }
    },
    
    // 暂停动画
    pauseSimulation: () => {
      try {
        if (specializedGraphRef.current && specializedGraphRef.current.pauseSimulation) {
          specializedGraphRef.current.pauseSimulation();
        } else if (mindMapRef.current && mindMapRef.current.pauseSimulation) {
          mindMapRef.current.pauseSimulation();
        } else if (flowChartRef.current && flowChartRef.current.pauseSimulation) {
          flowChartRef.current.pauseSimulation();
        } else if (orgChartRef.current && orgChartRef.current.pauseSimulation) {
          orgChartRef.current.pauseSimulation();
        }
      } catch (error) {
        errorHandler(new Error(`暂停动画失败: ${error.message}`));
      }
    },
    
    // 更新动画速度
    updateAnimationSpeed: (speed) => {
      try {
        if (specializedGraphRef.current && specializedGraphRef.current.updateAnimationSpeed) {
          specializedGraphRef.current.updateAnimationSpeed(speed);
        } else if (mindMapRef.current && mindMapRef.current.updateAnimationSpeed) {
          mindMapRef.current.updateAnimationSpeed(speed);
        } else if (flowChartRef.current && flowChartRef.current.updateAnimationSpeed) {
          flowChartRef.current.updateAnimationSpeed(speed);
        } else if (orgChartRef.current && orgChartRef.current.updateAnimationSpeed) {
          orgChartRef.current.updateAnimationSpeed(speed);
        }
      } catch (error) {
        errorHandler(new Error(`更新动画速度失败: ${error.message}`));
      }
    },
    
    // 导出图片
    exportImage: () => {
      try {
        if (specializedGraphRef.current && specializedGraphRef.current.exportImage) {
          specializedGraphRef.current.exportImage();
        } else if (mindMapRef.current && mindMapRef.current.exportImage) {
          mindMapRef.current.exportImage();
        } else if (flowChartRef.current && flowChartRef.current.exportImage) {
          flowChartRef.current.exportImage();
        } else if (orgChartRef.current && orgChartRef.current.exportImage) {
          orgChartRef.current.exportImage();
        }
      } catch (error) {
        errorHandler(new Error(`导出图片失败: ${error.message}`));
      }
    },
    
    // 获取图实例
    getGraph: () => {
      try {
        if (specializedGraphRef.current && specializedGraphRef.current.getGraph) {
          return specializedGraphRef.current.getGraph();
        } else if (mindMapRef.current && mindMapRef.current.getGraph) {
          return mindMapRef.current.getGraph();
        } else if (flowChartRef.current && flowChartRef.current.getGraph) {
          return flowChartRef.current.getGraph();
        } else if (orgChartRef.current && orgChartRef.current.getGraph) {
          return orgChartRef.current.getGraph();
        }
        return null;
      } catch (error) {
        errorHandler(new Error(`获取图实例失败: ${error.message}`));
        return null;
      }
    },

    // 重置布局
    resetLayout: () => {
      try {
        if (specializedGraphRef.current && specializedGraphRef.current.resetLayout) {
          specializedGraphRef.current.resetLayout();
        }
      } catch (error) {
        errorHandler(new Error(`重置布局失败: ${error.message}`));
      }
    },

    // 获取插件系统信息
    getPluginInfo: () => {
      return {
        isModular: false,
        currentPlugin: null,
        supportedGraphTypes: ['knowledge', 'mind', 'flow', 'org', 'social', 'concept'],
        supportedLayouts: ['force', 'circular', 'hierarchical', 'grid', 'radial', 'tree']
      };
    },
    
    // 更新布局
    updateLayout: (newLayout, newLayoutConfig) => {
      console.log('🔧 GraphVisualizationHub 接收到布局更新:', newLayout, newLayoutConfig);
      try {
        if (specializedGraphRef.current && specializedGraphRef.current.updateLayout) {
          specializedGraphRef.current.updateLayout(newLayout, newLayoutConfig);
        } else if (mindMapRef.current && mindMapRef.current.updateLayout) {
          mindMapRef.current.updateLayout(newLayout, newLayoutConfig);
        } else if (flowChartRef.current && flowChartRef.current.updateLayout) {
          flowChartRef.current.updateLayout(newLayout, newLayoutConfig);
        } else if (orgChartRef.current && orgChartRef.current.updateLayout) {
          orgChartRef.current.updateLayout(newLayout, newLayoutConfig);
        }
        // 强制重新渲染
        setRenderKey(prev => prev + 1);
      } catch (error) {
        errorHandler(new Error(`更新布局失败: ${error.message}`));
      }
    }
  }));

  // 根据图谱类型选择合适的可视化组件
  const renderVisualization = () => {
    let validNodes = [];
    let validEdges = [];
    
    try {
      // 确保节点和边数据有效
      validNodes = Array.isArray(nodes) ? nodes.filter(node => node && node.id) : [];
      validEdges = Array.isArray(edges) ? edges.filter(edge => {
        try {
          if (!edge || !edge.source || !edge.target) return false;
          
          const sourceId = typeof edge.source === 'object' ? edge.source.id : edge.source;
          const targetId = typeof edge.target === 'object' ? edge.target.id : edge.target;
          
          return validNodes.some(n => n.id === sourceId) && 
                 validNodes.some(n => n.id === targetId);
        } catch (error) {
          errorHandler(new Error(`处理边数据时出错: ${error.message}`));
          return false;
        }
      }) : [];
    } catch (error) {
      errorHandler(new Error(`处理图谱数据时出错: ${error.message}`));
      validNodes = [];
      validEdges = [];
    }

    const commonProps = {
      nodes: validNodes,
      edges: validEdges,
      onNodeClick,
      onEdgeClick,
      onNodePositionUpdate,
      editable,
      width,
      height,
      zoom,
      animationSpeed,
      isSimulationRunning,
      isFullscreen,
      onToggleFullscreen,
      errorHandler
    };

    try {
      switch (graphType) {
        case 'mind':
          return (
            <MindMapVisualization 
              {...commonProps} 
              ref={mindMapRef}
            />
          );
        
        case 'flow':
          return (
            <FlowChartVisualization 
              {...commonProps} 
              ref={flowChartRef}
            />
          );
        
        case 'org':
          return (
            <OrgChartVisualization 
              {...commonProps} 
              ref={orgChartRef}
            />
          );
          
        case 'social':
        case 'network':
        case 'concept':
        case 'ontology':
        case 'semantic':
        case 'knowledge':
          return (
            <SpecializedGraphVisualization 
              {...commonProps}
              graphType={graphType}
              layout={layout}
              layoutConfig={layoutConfig}
              onLayoutChange={onLayoutChange}
              ref={specializedGraphRef}
              key={`specialized-${renderKey}-${layout}`}
            />
          );
        
        // 对于中文图谱类型的映射
        case 'AI领域':
        case 'ai领域':
        case '技术':
        case '架构':
        case '安全':
        case '移动端':
        case '创新':
          return (
            <SpecializedGraphVisualization 
              {...commonProps}
              graphType="knowledge"
              layout={layout}
              layoutConfig={layoutConfig}
              onLayoutChange={onLayoutChange}
              ref={specializedGraphRef}
            />
          );
        
        default:
          try {
            // 尝试确定最合适的图谱类型
            let bestGraphType = "knowledge"; // 默认使用知识图谱
            
            // 如果有特定的图谱类型标识，尝试使用
            if (typeof graphType === 'string') {
              if (graphType.includes('思维') || graphType.includes('mind')) {
                bestGraphType = 'mind';
              } else if (graphType.includes('流程') || graphType.includes('flow')) {
                bestGraphType = 'flow';
              } else if (graphType.includes('社交') || graphType.includes('social')) {
                bestGraphType = 'social';
              } else if (graphType.includes('概念') || graphType.includes('concept')) {
                bestGraphType = 'concept';
              } else if (graphType.includes('本体') || graphType.includes('ontology')) {
                bestGraphType = 'ontology';
              }
            }
            
            return (
              <SpecializedGraphVisualization 
                {...commonProps}
                graphType={bestGraphType}
                layout={layout || 'force'} // 确保始终有布局
                layoutConfig={layoutConfig}
                onLayoutChange={onLayoutChange}
                ref={specializedGraphRef}
                key={`default-${renderKey}-${layout}`}
              />
            );
          } catch (error) {
            errorHandler(new Error(`渲染图谱失败: ${error.message}`));
            // 最终回退方案 - 使用最基本的力导向布局
            return (
              <SpecializedGraphVisualization 
                {...commonProps}
                graphType="knowledge"
                layout="force"
                layoutConfig={layoutConfig}
                onLayoutChange={onLayoutChange}
                ref={specializedGraphRef}
              />
            );
          }
      }
    } catch (error) {
      errorHandler(new Error(`选择图谱类型时出错: ${error.message}`));
      // 最终回退方案 - 使用最基本的力导向布局
      return (
        <SpecializedGraphVisualization 
          {...commonProps}
          graphType="knowledge"
          layout="force"
          layoutConfig={layoutConfig}
          onLayoutChange={onLayoutChange}
          ref={specializedGraphRef}
        />
      );
    }
  };

  return renderVisualization();
});

GraphVisualizationHub.displayName = 'GraphVisualizationHub';

export default GraphVisualizationHub;